﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Business
{
    public partial class crm_black_list
    {
        private static Dictionary<string, bool> _dictInstanct;
        private static readonly object _lock = new object();
        public static Dictionary<string, bool> DictInstanct
        {
            get
            {
                if (_dictInstanct == null)
                {
                    lock (_lock)
                    {
                        _dictInstanct = new Dictionary<string, bool>();
                        LoadData();
                    }
                }
                return _dictInstanct;
            }
        }
        public static string SelectCommand
        {
            get { return "SELECT subscriber, enabled FROM dbo.crm_black_list"; }
        }

        private static void LoadData()
        {
            using (SqlConnection conn = new SqlConnection(Settings.LocalSettings.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = SelectCommand;
                    LoadData(cmd);
                }
            }
        }

        private static void LoadData(SqlCommand cmd)
        {
            using (SqlDataReader rd = cmd.ExecuteReader())
            {
                while (rd.Read())
                {
                    _dictInstanct.Add((string)rd["subscriber"], (bool)rd["enabled"]);
                }
            }
        }

        public static void ReloadData(SqlCommand cmd)
        {
            lock (_lock)
            {
                if (_dictInstanct == null)
                    _dictInstanct = new Dictionary<string, bool>();
                else
                    _dictInstanct.Clear();
                LoadData(cmd);
            }
        }

        public static void ReloadData()
        {
            lock (_lock)
            {
                if (_dictInstanct == null)
                    _dictInstanct = new Dictionary<string, bool>();
                else
                    _dictInstanct.Clear();
                LoadData();
            }
        }
    }
}
